package sever

import (
	"0306zk/common/initialize"
	"0306zk/common/proto/user"
	"0306zk/rpc/mobile"
	"context"
	"fmt"
	"math/rand"
	"time"
)

func Login(in *user.LoginReq) (*user.LoginResp, error) {
	m := mobile.User{}

	get := initialize.Client.Get(context.Background(), "SendSmslogin"+in.Mobile)

	incr := initialize.Client.Incr(context.Background(), "SendIncr"+in.Mobile)

	if incr.Val() == 1 {
		initialize.Client.Expire(context.Background(), "SendIncr"+in.Mobile, time.Minute*60)
	}

	if get.Val() != in.Code {
		if incr.Val() >= 3 {
			return nil, fmt.Errorf("验证码错误三次,账户锁定一个小时")
		}
		return nil, fmt.Errorf("登录失败,验证码错误")
	}

	users, err := m.GetUserMobile(in.Mobile)
	if err != nil {
		return nil, fmt.Errorf("登录失败,账号未注册")
	}
	if users.Password != in.Password {
		return nil, fmt.Errorf("登录失败,密码错误")
	}

	initialize.Client.Del(context.Background(), "SendSmslogin"+in.Mobile)
	initialize.Client.Del(context.Background(), "SendIncr"+in.Mobile)

	return &user.LoginResp{Id: int64(users.ID)}, err
}
func Register(in *user.RegisterReq) (*user.RegisterResp, error) {
	m := mobile.User{}

	get := initialize.Client.Get(context.Background(), "SendSmsregister"+in.Mobile)

	if get.Val() != in.Code {
		return nil, fmt.Errorf("注册失败,验证码错误")
	}

	users, err := m.GetUserMobile(in.Mobile)
	if users != nil {
		return nil, fmt.Errorf("注册失败,账号已被注册")
	}
	_, err = m.CreateRegister(in.Mobile, in.Password)
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &user.RegisterResp{Success: true}, err
}
func SendSms(in *user.SendSmsReq) (*user.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000

	//sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if *sms.Body.Code != "ok" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}

	initialize.Client.Set(context.Background(), "SendSms"+in.Source+in.Mobile, code, time.Minute*3)

	return &user.SendSmsResp{Success: true}, nil
}
